package com.project.serviceImpl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.server.HttpServerRequest;
import cn.hutool.http.server.HttpServerResponse;
import com.project.service.UploadService;
import com.project.utils.token.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;

/**
 * @author : Mr.Yan
 * @program : com.project.serviceImpl
 * @create : 2020/09/02
 * @description : 这是实现上传文件接口的实现类
 */
@Slf4j
@Service
@Transactional
public class UploadServiceImpl implements UploadService {

    @Value("${upload.path}")
    private String uploadPath; // 上传文件的前缀

    @Value("${upload.locations}")
    private String uploadLocations; // 上传文件地址

    @Override
    public String uploadFile(MultipartFile file) {
        String filename = file.getOriginalFilename();

        // 获取文件扩展名，如 abc.de.jpg，就获取 jpg
        String extensionName = filename.substring(filename.lastIndexOf(".") + 1);
        // 设置上传文件的文件名，防止命名冲突导致覆盖
        String uploadFilename = UUID.randomUUID().toString() + "." + extensionName;

        File uploadDir = new File(uploadLocations);
        // 检查上传路径是否存在，不存在则创建
        if (!uploadDir.exists()) {
            log.info("上传路径不存在，创建路径");
            // 设置可读权限，因为启用 tomcat 的用户可能没有写文件的权限
            uploadDir.setWritable(true);
            boolean createDirResult = uploadDir.mkdirs();
            log.info("文件的读权限：{}，文件的写权限：{}，创建结果：{}",
                    uploadDir.canRead(), uploadDir.canWrite(), createDirResult);
        }
        File targetFile = new File(uploadDir, uploadFilename);

        try {
            file.transferTo(targetFile);
            // TODO 将 targetFile 上传到文件服务器上，上传完成后，删除 uploadDir 下的文件
            // targetFile.delete();
        } catch (IOException e) {
            log.error("文件上传异常：", e);
            return null;
        }
        log.info("文件路径：{}，文件名：{}", targetFile.getAbsolutePath(), targetFile.getName());
        if(uploadPath.equals("/"))
            return targetFile.getName();
        return uploadPath + "/" + targetFile.getName();
    }

    @Override
    public String uploadImage(MultipartFile file) {
        String fileStr = "";
        try {
            // 检测文件大小
            if (file.isEmpty()) {
                throw new CustomException("请选择图片");
            }
            //检查是否是图片
            BufferedImage bi = ImageIO.read(file.getInputStream());
            if (bi == null) {
                throw new CustomException("请上传图片类型");
            }
            // 转换为base64编码格式
            BASE64Encoder encoder = new BASE64Encoder();
            fileStr = encoder.encode(file.getBytes());
            fileStr = fileStr.replaceAll("[\\s*\t\n\r]", "");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "data:" + file.getContentType() + ";base64," + fileStr;
    }

}
